package pl.softech.server.http;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import pl.softech.server.IRequestHandler;

public class HttpStaticContent implements IRequestHandler {

    private String getTxtFileContent(File file) throws IOException {
        StringBuilder ret = new StringBuilder();
        BufferedReader bin = null;
        try {
            bin = new BufferedReader(new FileReader(file));
            String line;
            while ((line = bin.readLine()) != null) {
                ret.append(line + "\n");
            }
        } finally {
            if (bin != null) {
                bin.close();
            }
        }
        return ret.toString();
    }

    @Override
    public HttpResponse handle(HttpRequest request, HttpResponse response) throws Exception {
        try {
            File file = new File(request.getUri().getPath());
            String fileContent = getTxtFileContent(file);
            response.setContent(fileContent);

        } catch (Exception e) {
            StringWriter out = new StringWriter();
            PrintWriter pout = new PrintWriter(out);
            e.printStackTrace(pout);
            response.setContent("<html>" + out.getBuffer().toString() + "</html>");
        }
        return response;
    }

    @Override
    public boolean match(HttpRequest request) {
        return true;
    }

}
